var ObjectsManager = Class.create({
    initialize: function () {
        this.objects = new Array();
    },
    add: function (myObject) {
        this.objects.push(myObject);
    },
    remove: function(o){
        var found = false;
        //can be id or objects
        if( typeof o === "string"){
            for(var i = 0 ; i < this.objects. length ; i++){
                if(this.objects[i].id == o){
                    this.objects = null;
                    found = true;
                    break;
                }
            }
        }
        else{
            for(var i = 0 ; i < this.objects. length ; i++){
                if(this.objects[i] === o){
                    this.objects = null;
                    found = true;
                    break;
                }
            }
        }

        if(found){
            this.objects = this.objects.compact();
            return true;
        }
        return false;
    },
    start: function () {
        var _this = this;
        this.timerHandler = setInterval(function () {
            //Update tat ca object o day
            _this.updateObjects(_this.objects);
            //_this.drawObjects(_this.objects);
        }, 40);

//        (function animationLoop(){
//            window.requestAnimationFrame(animationLoop);
//            _this.updateObjects();
//        })();
    },
    stop: function () {
        clearInterval(this.timerHandler);
    },
    updateObjects: function () {
        this.objects.each(function (item) {
            item.update();
        });
    },
    drawObjects: function (objects) {
        objects.each(function (item) {
            item.draw();
        });
    },
    getElementById: function (id) {
        var returnVal = null;

        for (var i = 0; i < this.objects.length; i++) {
            returnVal = this.objects[i].getElementById(id);
            if(returnVal !== null){
                break;
            }
        }

        return returnVal;
    },
    getElementByTouch: function(x, y){
        var isInside = function(x, y, top, left, width, height){
            return ((x>= left && x <= left + width)
                && (y >= top && y <= top + height));
        };

        var highestZIndex = 0;
        var retVal;

        for(var i =0 ; i < this.objects.length ; i++){
            var layout = $(this.objects[i].divTag).getLayout();
            var width = layout.get("width");
            var height = layout.get("height");
            var top = layout.get("top");
            var left = layout.get("left");
            if(isInside(x, y, top, left, width, height) && this.objects[i].isVisible()
                && this.objects[i].getZIndex() >= highestZIndex){
                retVal = this.objects[i];
                highestZIndex = this.objects[i].getZIndex();
            }
        }
        return retVal;
    }

});